package com.cnhis.cloudhealth.clinical.clidoctor.clibackadvice.bo;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cnhis.cloudhealth.clinical.clidoctor.clibackadvice.dao.CliBackAdviceDao;
import com.cnhis.cloudhealth.clinical.clidoctor.clinewadvice.dao.CliNewAdviceDao;
import com.cnhis.cloudhealth.clinical.clidoctor.clisendadvice.dao.CliSendAdviceDao;
import com.cnhis.cloudhealth.commons.Mappers.ModelVo;
import com.cnhis.cloudhealth.commons.commonSql.bo.YaopinKucunBo;
import com.cnhis.cloudhealth.commons.utils.DateUtils;
import java.util.HashMap;
import com.cnhis.cloudhealth.commons.utils.StaticKeys;
@SuppressWarnings("rawtypes")
@Service
public class CliBackAdviceBo {
	@Resource
	private CliNewAdviceDao cliNewAdviceDao;
	@Resource
	private CliBackAdviceDao cliBackAdviceDao;
	@Resource
    private CliSendAdviceDao cliSendAdviceDao;
	@Resource
    private YaopinKucunBo yaopinKucunBo;
	public ModelVo getclinicEditOrderBeforeJudge(Map map) throws Exception {
		
		ModelVo mo = new ModelVo(StaticKeys.OH_SUCCESS);
		
		//如果是非门诊，则返回成功
		if(!"1".equals(map.get("ACF01").toString())){
			return mo;
		}
		//是否有限制条件
		if(getBlp02(map)){
			return mo;
		}
		
		//获取限定年龄
		Integer BLP04 = getBlp04(map);
		
		//获取病人年龄
		Integer VAA10 = getVaa10(map);
		
		if((VAA10>=BLP04)&&getVcj04Vcj05(map)){
			mo.setResult(StaticKeys.OH_FALSE);
			mo.setResultMsg("病人超过"+BLP04+"岁，必须要输入收缩压和舒张压.");
			return mo;
		}
		
		return mo;
	}

	/**
	 * 入收缩压和舒张压 是否为空
	 * @param map
	 * @return
	 * @throws Exception 
	 */
	private boolean getVcj04Vcj05(Map map) throws Exception {
		int ct = cliNewAdviceDao.getVcj04Vcj05(map);
		if(ct>0){
			return true;
		}
		return false;
	}

	/**
	 * 获取病人年龄
	 * @param map
	 * @return
	 * @throws Exception 
	 */
	private Integer getVaa10(Map map) throws Exception {
		Integer VAA10 = cliNewAdviceDao.getVaa10(map);
		VAA10 = VAA10==null?0:VAA10;
		return VAA10;
	}

	/**
	 * 获取限定年龄
	 * @param map
	 * @return
	 * @throws Exception 
	 */
	private Integer getBlp04(Map map) throws Exception {
		Integer BLP04 = cliNewAdviceDao.getBlp04(map);
		BLP04 = BLP04==null?0:BLP04;
		return BLP04;
	}

	/**
	 * 是否有限制条件
	 * @param map
	 * @return
	 * @throws Exception
	 */
	private boolean getBlp02(Map map) throws Exception {
		int ct = cliNewAdviceDao.getBlp02(map);
		if(ct==0){
			return true;
		}
		return false;
	}
	
	public ModelVo  judgeBackAdvice(Map map) throws Exception{
		ModelVo mo = new ModelVo();
		List list =null;
		try {
			list=cliBackAdviceDao.judgeBackAdvice(map);
			
		} catch (Exception e) {
			e.printStackTrace();
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		mo.setList(list);
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setRows(list);
		return mo;
	}
	//验证是否有退单
	private boolean findBackAdviceParam(Map map)throws Exception{
		return cliBackAdviceDao.findBackAdviceParam(map)==0;
	}
	//获取权限参数
	private String getApara269()throws Exception{
		return cliBackAdviceDao.getApara269();
	}
	//判断医嘱单结帐转移
	private boolean getVBI05(Map map)throws Exception{
		return cliBackAdviceDao.getVBI05(map)>0;
	}
	//检查是否上传医保
	private Integer checkMedicare(Map map)throws Exception{
		return cliBackAdviceDao.checkMedicare(map);
	}
	//医嘱单是否已经结帐
	private Integer checkSettleAccounts(Map map)throws Exception{
		
		return cliBackAdviceDao.checkSettleAccounts(map);
	}
	private Integer checkSettleAccounts1(Map map)throws Exception{
		
		return cliBackAdviceDao.checkSettleAccounts1(map);
	}
   //医嘱是否安排手术
	private Integer BPL37()throws Exception{
		return cliBackAdviceDao.BLP137();
	}
	private String VAF22(Map map)throws Exception{
		return cliBackAdviceDao.VAF22(map);
	}
	//是否有回退医嘱明细
	private Integer checkReturnDetail(Map map)throws Exception{
		return cliBackAdviceDao.checkReturnDetail(map);
	}
	/**
	 * 修改门诊单据表 作废单据
	 * 修改门诊病人费用明细表 作废记录
	 * 修改门诊病人医嘱表
	 * 删除门诊病人医嘱抄送记录
	 * 删除医嘱计价记录
	 * @param map
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private void updateAndDelete(Map map)throws Exception{
		String lDate = DateUtils.getDateString(new Date());
		map.put("lDate", lDate);
		cliBackAdviceDao.updateAndDelete_VAI1_VAJ1_VAF1_VBI1_VBD1(map);
	}
	//医嘱状态记录
	private void insertAndDelete(Map map)throws Exception{
		cliBackAdviceDao.insertAndDelete(map);
	}
	//是否处理库存
	private Integer updateStockParam(Map map)throws Exception{
		return cliBackAdviceDao.updateStockParam(map);
	}
	//库存处理
	public void updateStock(Map map)throws Exception{
		
		  cliBackAdviceDao.updateStock(map);
	}
	//修改库存参数
	private List DPS_DPT1_Update_Param(Map map)throws Exception{
		return cliBackAdviceDao.DPS_DPT1_Update_Param(map);
	}

	@SuppressWarnings("unchecked")
	public List DPSDPT1(List list)throws Exception{
		Double updQty =0d;
		Double refQty=0d;
		Double sellQty=0d,quantity=0d;
		for (int i = 0; i < list.size(); i++) {
			Map m = (Map) list.get(i);
			m.put("ROW_NAME", "DSK_ID");
//			m.put("dsk01", Integer.parseInt(m.get("dsk01").toString()));
			Map map = getRefQtyAndSellQty(m);
			if(map==null)
			{
			    continue;
			}
			m.put("updqty", m.get("vaj25"));
			m.put("dsk01", map.get("dsk_id"));
			String RefQty = map.get("refqty")==null||"".equals(map.get("refqty").toString())?"0":map.get("refqty").toString();
			String SellQty = map.get("refqty")==null||"".equals(map.get("sellqty").toString())?"0":map.get("sellqty").toString();
			String Quantity = map.get("quantity")==null||"".equals(map.get("quantity").toString())?"0":map.get("quantity").toString();
			refQty = Double.parseDouble(RefQty);
			sellQty = Double.parseDouble(SellQty);
			quantity = Double.parseDouble(Quantity);
			String UpdQty=m.get("updqty")==null||"".equals(m.get("updqty").toString())?"0":m.get("updqty").toString();
			updQty = Double.parseDouble(UpdQty);
			if(updQty>0){//增加预扣数
				if(updQty + sellQty <= refQty){
				   select_tmp_DPT1_param1(m);
					updQty=0d;
				}else{
					
				    select_tmp_DPT1_param2(m);
				    updQty = updQty - (refQty - sellQty);
				}
				m.put("UpdQty", updQty);
				
				if(updQty!=0){
					m.put("list", list);
					Map maps = getMaxAndMin(m);
					int max = Integer.parseInt(maps.get("itatol").toString());
					int min = Integer.parseInt(maps.get("icount").toString());
					for (;min <= max; min++) {
						m.put("list", list);
						m.put("ROW_NAME", "XROWNUM");
						m.put("DSK_ID", min);
						map = getRefQtyAndSellQty1(m);
						if (map!=null)
                        {
                            RefQty = map.get("refqty") == null || "".equals(map.get("refqty").toString()) ? "0"
                                : map.get("refqty").toString();
                            SellQty = map.get("refqty") == null || "".equals(map.get("sellqty").toString()) ? "0"
                                : map.get("sellqty").toString();
                            refQty = Double.parseDouble(RefQty);
                            sellQty = Double.parseDouble(SellQty);
                            if (updQty + sellQty <= refQty)
                            {
                                select_tmp_DPT1_param3(m);
                                
                                updQty = 0d;
                                m.put("UpdQty", updQty);
                                break;
                            }
                            select_tmp_DPT1_param4(m);
                            updQty = updQty - (refQty - sellQty);
                            m.put("UpdQty", UpdQty);
                        }
					}
				}
			}else if(updQty<0){//减少预扣数
				if(updQty + sellQty >= 0){
					
					select_tmp_DPT1_param5(m);
					updQty=0d;
				}else{
					
					select_tmp_DPT1_param6(m);
					updQty = updQty + sellQty;
				}
				m.put("UpdQty", updQty);
                if(updQty!=0){
                	m.put("list", list);
                	Map maps = getMaxAndMin(m);
					int max = Integer.parseInt(maps.get("itatol").toString());
					int min = Integer.parseInt(maps.get("icount").toString());
					for (; min <= max; min++) {
						m.put("list", list);
						m.put("ROW_NAME", "XROWNUM");
						m.put("DSK_ID", min);
						map = getRefQtyAndSellQty1(m);
						RefQty = map.get("refqty")==null||"".equals(map.get("refqty").toString())?"0":map.get("refqty").toString();
					    SellQty = map.get("refqty")==null||"".equals(map.get("sellqty").toString())?"0":map.get("sellqty").toString();
						refQty = Double.parseDouble(RefQty);
						sellQty = Double.parseDouble(SellQty);
						if(updQty + sellQty >= 0){
							
							        select_tmp_DPT1_param7(m);
							        updQty = 0d;
							        m.put("UpdQty", updQty);
									break;
						}
						select_tmp_DPT1_param8(m);
						updQty = updQty + sellQty;
						m.put("UpdQty", updQty);
					}
                }
			}
//			updateStock(m);
		}
		return list;
	}
	
	private Map getRefQtyAndSellQty(Map map)throws Exception{
		return cliBackAdviceDao.getRefQtyAndSellQty(map);
	}
	private Map getRefQtyAndSellQty1(Map map)throws Exception{
		return cliBackAdviceDao.getRefQtyAndSellQty1(map);
	}
	private List select_tmp_DPT1_param1(Map map)throws Exception{
		return cliBackAdviceDao.select_tmp_DPT1_param1(map);
	}
	private List select_tmp_DPT1_param2(Map map)throws Exception{
		 return cliBackAdviceDao.select_tmp_DPT1_param2(map);
	}
	private List select_tmp_DPT1_param3(Map map)throws Exception{
		return cliBackAdviceDao.select_tmp_DPT1_param3(map);
	}
	private List select_tmp_DPT1_param4(Map map)throws Exception{
		 return cliBackAdviceDao.select_tmp_DPT1_param4(map);
	}
	private List select_tmp_DPT1_param5(Map map)throws Exception{
		return cliBackAdviceDao.select_tmp_DPT1_param5(map);
	}
	private List select_tmp_DPT1_param6(Map map)throws Exception{
		 return cliBackAdviceDao.select_tmp_DPT1_param6(map);
	}
	private List select_tmp_DPT1_param7(Map map)throws Exception{
		return cliBackAdviceDao.select_tmp_DPT1_param7(map);
	}
	private List select_tmp_DPT1_param8(Map map)throws Exception{
		 return cliBackAdviceDao.select_tmp_DPT1_param8(map);
	}
	private Map getMaxAndMin(Map map)throws Exception{
		return cliBackAdviceDao.getMaxAndMin(map);
	}
	//医嘱回退---暂时不用
	@SuppressWarnings("unchecked")
	public ModelVo execClinicSendAdviceBlank(Map map) throws Exception{
		ModelVo mo = new ModelVo();
		List list =null;
		try {
			if(findBackAdviceParam(map)){
				mo.setResult(StaticKeys.OH_FALSE);
				mo.setResultMsg("没有需要回退的医嘱单");
				return mo;
				
			}
			String apara269 = getApara269();
//			if("1".equals(map.get("lMember").toString())){
//				map.put("lVAJ04", 2);
//				map.put("lVAJ05", 0);
//			}else{
//				map.put("lVAJ04", 3);
//				map.put("lVAJ05", 1);
//			}
			if(getVBI05(map)){
				mo.setResult(StaticKeys.OH_FALSE);
				mo.setResultMsg("此医嘱单已结帐转移，不能在回退");
				return mo;
			}
			Integer check = checkMedicare(map);
			if(check!=null){
				mo.setResult(StaticKeys.OH_FALSE);
				mo.setResultMsg("医嘱单:"+check+"对应医保费用已上传，不能在回退，请刷新后在操作");
				return mo;
			}
			Integer cbm = checkSettleAccounts(map);
			if(!("-1".equals(apara269))&&cbm!=null){
				mo.setResult(StaticKeys.OH_FALSE);
				mo.setResultMsg("医嘱单:"+cbm+"已经结帐或已扣费，不能在回退");
				return mo;
			}
			cbm = checkSettleAccounts1(map);
			if("1".equals(apara269)&&cbm==0){
				mo.setResult(StaticKeys.OH_FALSE);
				mo.setResultMsg("医嘱单对应所有单据已经结帐或已扣费，不能在回退");
				return mo;
			}
			Integer BLP37 = BPL37();
			String VAF22 = VAF22(map);
			if(BLP37>0&&(VAF22!=null&&!"".equals(VAF22))){
				mo.setResult(StaticKeys.OH_FALSE);
				mo.setResultMsg(VAF22+"对应手术医嘱，手术室已安排，不能在回退此医嘱");
				return mo;
			}
			Integer vaf = checkReturnDetail(map);
			if(vaf==0){
				mo.setResult(StaticKeys.OH_FALSE);
				mo.setResultMsg("没有需要回退的医嘱明细");
				return mo;
			}
			
			updateAndDelete(map);
			//医嘱状态记录
			insertAndDelete(map);
			Integer temp = updateStockParam(map);
			if(temp>0){
				list = DPS_DPT1_Update_Param(map);
				if(list.size()==0){
					mo.setResult(StaticKeys.OH_FALSE);
					mo.setResultMsg("没有需要处理的库存");
					return mo;
				}
				//预处理库存
				String Para46 = getParameter(9999, 9999, 46);
				
	            if("0".equals(Para46))
	            {
	                yaopinKucunBo.updateDpsAndDpt(list);
	            }
			}
		} catch (Exception e) {
			e.printStackTrace();
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		mo.setResult(StaticKeys.OH_SUCCESS);
		return mo;
	}
	
	 @SuppressWarnings("unchecked")
	    private String getParameter(Integer productId, Integer programId, Integer paramNo)
	        throws Exception
	    {
	        HashMap map = new HashMap();
	        map.put("productId", productId);
	        map.put("programId", programId);
	        map.put("paramNo", paramNo);
	        return cliSendAdviceDao.getParameter(map);
	    }

    public void updateDpt1(Map params)
    {
        // TODO Auto-generated method stub
        
    }
	
}
